const { login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')

async function handleUserRouter(req, res){
    const method = req.method // GET POST

    // 登录
    if (method === 'POST' && req.path === '/api/user/login') {
        const { username, password } = req.body
        // const { username, password } = req.query 
        let result = await login(username, password)
        result = JSON.stringify(result)
        result = JSON.parse(result)
        if (result.username) {
            // 服务器向客户端存数据放入cookie中，并把cookie交给客户端   path=/ 整个应用下的路由都可以使用该cookie，httpOnly只允许后端更改cookie
            // res.setHeader('Set-Cookie', `username=${result.username}; path=/; httpOnly; expires=${getCookieExpires()}` )
            // 设置 session
            req.session.username = result.username
            req.session.password = password
            return new SuccessModel()
        }
        return new ErrorModel('登录失败')
    }

    // 登录验证的测试
    if (method === 'GET' && req.path === '/api/user/login-test') {
        if (req.session.username) {
            return Promise.resolve(new SuccessModel({session: req.session}))
        }
        return Promise.resolve(new ErrorModel('尚未登录'))
    }

}



module.exports = handleUserRouter